﻿using System;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace LCL.DbSqlMonitor
{
    internal static class Program
    {
        public const int WM_CLOSE = 16;
        [STAThread]
        private static void Main()
        {
            CultureInfo cultureInfo = new CultureInfo("zh-CN");
            Thread.CurrentThread.CurrentCulture = cultureInfo;
            Thread.CurrentThread.CurrentUICulture = cultureInfo;
            bool flag;
            using (new Mutex(true, Application.ProductName, out flag))
            {
                if (flag)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new SqlMonitor());
                }
                else
                {
                    new Thread(new ThreadStart(Program.KillMessageBox)).Start();
                    string @string = "已有一个SQL Monitor在运行,3秒后我会自动消失...";
                    MessageBox.Show(@string, "Warning Duplicate SQL Monitor", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    Application.Exit();
                }
            }
        }
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
        private static void KillMessageBox()
        {
            Thread.Sleep(3000);
            IntPtr intPtr = Program.FindWindow(null, "Warning Duplicate SQL Monitor");
            if (intPtr != IntPtr.Zero)
            {
                Program.PostMessage(intPtr, 16, IntPtr.Zero, IntPtr.Zero);
                Environment.Exit(0);
            }
        }
    }
}
